package com.sky.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.OrderDetailMapper;
import com.sky.result.Result;
import com.sky.service.OrderDetailService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.JwtUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@RestController("userOrderController")
@RequestMapping("/user/order")
@Slf4j
@Api(tags = "C端-订单接口")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/submit")
    @ApiOperation("用户下单")
    public Result<OrderSubmitVO> submitOrder(@RequestBody OrdersSubmitDTO ordersSubmitDTO) {
        OrderSubmitVO orderSubmitVO = orderService.submitOrder(ordersSubmitDTO);
        return Result.success(orderSubmitVO);
    }


    @GetMapping("/historyOrders")
    @ApiOperation("分页查询历史订单")
    public Result<IPage<OrderVO>> historyOrders4Customer(OrdersPageQueryDTO dto, @RequestHeader String authentication){
        // 从认证信息中解析用户ID
        Long userId = JwtUtil.parseJWT(authentication).get("userId", Long.class);

        //分页查询
        Page<Orders> page = new Page<>(dto.getPage(), dto.getPageSize());
        orderService.query()
                .eq("user_id", userId)
                .eq(dto.getStatus()!=null, "status", dto.getStatus())
                .orderByDesc("order_time")
                .page(page);

        //将Orders转换成OrderVO
        IPage<OrderVO> convert = page.convert(orders -> {
            OrderVO orderVO = BeanUtil.toBean(orders, OrderVO.class);
            //订单详情数据List查询出来
            List<OrderDetail> orderDetailList = orderDetailService.query().eq("order_id", orders.getId()).list();
            orderVO.setOrderDetailList(orderDetailList);
            return orderVO;
        });

        return Result.success(convert);
    }

    @GetMapping("/orderDetail/{id}")
    @ApiOperation("订单详情")
    public Result<OrderVO> details(@PathVariable("id") Long id) {
        Orders orders = orderService.getById(id);
        OrderVO orderVO = BeanUtil.toBean(orders, OrderVO.class);
        List<OrderDetail> orderDetailList = orderDetailService.query().eq("order_id", orders.getId()).list();
        orderVO.setOrderDetailList(orderDetailList);
        return Result.success(orderVO);
    }

    @PutMapping("/cancel/{id}")
    @ApiOperation("取消订单")
    public Result<Void> cancel(@PathVariable("id") Long id) {
        orderService.update()
                .eq("id", id)
                .set("status", Orders.CANCELLED)
                .update();
        return Result.success();
    }

    @PostMapping("/repetition/{id}")
    @ApiOperation("再来一单")
    public Result<Void> repetition(@PathVariable Long id, @RequestHeader String authentication) {
        // 从认证信息中解析用户ID
        Long userId = JwtUtil.parseJWT(authentication).get("userId", Long.class);

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailService.query().eq("order_id", id).list();

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtil.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartService.saveBatch(shoppingCartList);
        return Result.success();
    }

}